package com.hntx.joymusic.receiver;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.UsbFile;

public class UsbReceiver extends BroadcastReceiver {
    private static final String TAG = "UsbReceiver";
    private Context context;
    String mountPath = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {//ACTION_MEDIA_REMOVED
            mountPath = intent.getData().getPath();
            Log.d(TAG, "mountPath = " + mountPath);
            Toast.makeText(context, "mounthPath:" + mountPath, Toast.LENGTH_LONG).show();
            if (!TextUtils.isEmpty(mountPath)) {
                redUDiskDevsList();
            }
        }//如果是开机完成，则需要调用另外的方法获取U盘的路径
    }

    private UsbMassStorageDevice[] storageDevices;
    private UsbFile cFolder;
    public static final String ACTION_USB_PERMISSION = "com.example.usbreadwriterdaemon.USB_PERMISSION";

    private void redUDiskDevsList() {
        //设备管理器
        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        //获取U盘存储设备
        storageDevices = UsbMassStorageDevice.getMassStorageDevices(context);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                0, new Intent(ACTION_USB_PERMISSION), 0);
        for (UsbMassStorageDevice device : storageDevices) {
            //读取设备是否有权限
            if (!usbManager.hasPermission(device.getUsbDevice())) {
                usbManager.requestPermission(device.getUsbDevice(), pendingIntent);
//                if (mountPath != null) {
//                    File file = new File("mnt/usb/sda1/apks/");
//                    if (file.exists()) {
//                        File[] files = file.listFiles();
//                        for (int i = 0; i < files.length; i++) {
//                            Log.d("显示文件：", files[i].getName());
//                        }
//                    }
//                }
            }
//            else {
//                //没有权限，进行申请
//
//            }
        }
    }
}
